#include "ItemParticle.h"
#include "Resources.h"

ItemParticle::ItemParticle(ofPoint loc, ofPoint vel, int ID, float ttl, float dumbTime) :
Particle(loc, vel, 300), ID(ID), theta(0.0f), scale(1.0f), killed(false),
timeKilled(0.0f), dumbTime(dumbTime)
{
}

ItemParticle::~ItemParticle(void)
{
}

bool ItemParticle::update() {
    theta += 1.0f;
    bool dead;
    float timeSinceKilled = ofGetElapsedTimef()-timeKilled;

    if (killed) {
        vel.set(0.0f, 0.0f);
        if (timeSinceKilled < ITEM_PARTICLE_DEATH_DURATION) {
            float m     = (timeSinceKilled)/ITEM_PARTICLE_DEATH_DURATION;
            scale       = ofLerp(1.0f, 0.0f, m);
            locOffset.x = ofLerp(0.0f, locOffsetTarget.x, m);
            locOffset.y = ofLerp(0.0f, locOffsetTarget.y, m);
        } else {
            return true;
        }
    }

    if (dead = positionAndTtlUpdate()) return true;

    return false;
}

void ItemParticle::draw() {
    ofPushMatrix();
    ofTranslate(loc.x+locOffset.x, loc.y+locOffset.y + 0.414f + sinf(theta/20.0f)/10.0f);
    ofRotate(theta);

    ofScale(scale/2, scale/2);

    ofTranslate(-0.5f, -0.5f);

    glCallList(Resources::get()->terrainListByID(ID));
    ofPushStyle();
    ofSetColor(0x000000);
    ofNoFill();
    ofEnableSmoothing();
    ofRect(0, 0, 1, 1);
    ofPopStyle();

    ofPopMatrix();
}

bool ItemParticle::kill(float xOffset, float yOffset) {
    if (killed) return false;
    if (ofGetElapsedTimef() - t_created < dumbTime) return false;

    timeKilled = ofGetElapsedTimef();

    locOffsetTarget.set(xOffset, yOffset);

    killed = true;

    return true;
}

int ItemParticle::getID() {
    return ID;
}

bool ItemParticle::hasBeenKilled() {
    return killed;
}
